package org.jrpc.client2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.jrpc.base.IClient;
import org.jrpc.base.ResultResponse;
import org.jrpc.client3.ConnectionListener;
import org.jrpc.common.baen.RpcRequest;
import org.jrpc.common.baen.RpcResponse;
import org.jrpc.common.codec.RpcDecoder;
import org.jrpc.common.codec.RpcEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * RPC 客户端（用于发送 RPC 请求）
 * @since 1.0.0
 */
@Deprecated
public class RpcClient extends Thread implements IClient {

    private static final Logger logger = LoggerFactory.getLogger(RpcClient.class);

    private final String host;

    private final int port;

    private ConcurrentHashMap<String,ResultResponse> map=new ConcurrentHashMap<>();

    private RpcClientHandler rpcClientHandler = new RpcClientHandler(map);

    private EventLoopGroup group = new NioEventLoopGroup();

    public static void main(String[] args) throws IOException {
       /* RpcClient rpcClient = new RpcClient("127.0.0.1", 9080);
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        rpcClient.send();
        for(int t=0;t<2;t++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    long startTime=System.currentTimeMillis();
                    RpcRequest msg = null;
                    for(int i=0;i<5000;i++){
                        msg = new RpcRequest("abc_"+i);
                        try {
                            rpcClient.rpcClientHandler.sendMsg(msg);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("endTime:"+(System.currentTimeMillis()-startTime) );
                }
            }).start();
        }*/


        /*@SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        RpcRequest msg = null;
        do{
            msg = new RpcRequest();
            msg.setRequestId(scanner.nextLine());
        }
        while (rpcClient.rpcClientHandler.sendMsg(msg)!=null);*/
    }

    public RpcClient(String host, int port) {
        this.host = host;
        this.port = port;
        this.start();
    }

    public void send() {
        try {
            RpcRequest msg = new RpcRequest("111");
            rpcClientHandler.sendMsg(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            init(group);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public RpcResponse init(EventLoopGroup eventLoop) throws Exception {

        try {
            // 创建并初始化 Netty 客户端 Bootstrap 对象
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoop);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(new RpcEncoder(RpcRequest.class)); // 编码 RPC 请求
                    pipeline.addLast(new RpcDecoder(RpcResponse.class)); // 解码 RPC 响应
                    pipeline.addLast(rpcClientHandler); // 处理 RPC 响应
                }
            });
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            // 连接 RPC 服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
//            bootstrap.remoteAddress(host, port);
//            bootstrap.connect().addListener(new ConnectionListener(this));
            future.addListener(new ConnectionListener(this));
            // 写入 RPC 请求数据并关闭连接
            Channel channel = future.channel();
//            channel.writeAndFlush(request).sync();
            channel.closeFuture().sync();

            // 返回 RPC 响应对象
            return null;
        } finally {
//            group.shutdownGracefully();
        }
    }

    @Override
    public Bootstrap createBootstrap(Bootstrap bootstrap, EventLoopGroup eventLoop) {
        return null;
    }

    @Override
    public ResultResponse put(RpcRequest request) {
        try {
            return rpcClientHandler.sendMsg(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
